<template>
  <div class="login">
    <h2>登录</h2>
    <el-form :model="loginForm" ref="loginForm" label-width="100px" :rules="formRules" @submit.prevent="login">
      <el-form-item label="账号" prop="phone">
        <el-input v-model="loginForm.phone" placeholder="请输入手机号或邮箱"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <el-button @click="toRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "@/utiles/axios";

export default {
  data() {
    return {
      loginForm: {
        phone: "",
        password: "",
      },
      formRules: {
        phone: [
          { required: true, message: "请输入手机号或邮箱", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, message: "密码长度不能小于 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 登录
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          axios
              .post("/student/login", this.loginForm)  // 发送手机号和密码
              .then((response) => {
                this.$message.success("登录成功！");

                // 获取学生 ID 和其他信息
                const studentData = response.data;
                if (studentData.id) {
                  // 登录成功后将 ID 存储到 localStorage 中
                  localStorage.setItem("studentId", studentData.id);  // 存储学生 ID
                  localStorage.setItem("studentName", studentData.name);// 存储学生姓名
                  localStorage.setItem("organizationId", studentData.organizationId);  // 存储学生所在组织 ID
                  localStorage.setItem("trainingId", studentData.trainingId)// 存储学生所在组织名称

                  console.log(localStorage)
                } else {
                  console.error('学生信息获取失败');
                }

                this.$router.push("/home");  // 登录成功后跳转到主页
              })
              .catch(() => {
                this.$message.error("账号或密码错误！");
              });
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    // 跳转到注册页面
    toRegister() {
      this.$router.push("/studentRegister");
    },
  },
};
</script>

<style>
.login {
  width: 400px;
  margin: 100px auto;
}
</style>
